import type {
  ComputeContext,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  CrudExpose,
} from '@fast-crud/fast-crud';

import type { Ref } from 'vue';

import type { ExtendedModalApi } from '@vben/common-ui';
import type { Undefinedable } from '@vben/types';

import type { FormRulesExt } from '#/api';
import type { SopIsvInfoModel } from '#/api/devOperation/sop/model/sopIsvInfoModel';

import { ref } from 'vue';

import { useAccess } from '@vben/access';
import { $t } from '@vben/locales';

import { compute, dict } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';

import { DefTenantApi } from '#/api';
import { SopIsvInfoApi } from '#/api/devOperation/sop/sopIsvInfo';
import { ActionEnum, AuditStatusEmum, DictEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import { CreationMethodEnum } from '#/enums/sop';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  DictValueType,
  indexColumn,
  STATE_NUMBER_CONSTANT_DICT,
} from '#/plugins/fast-crud/common';

const { hasPermission } = useAccess();
const permCode = PermCode.devOperation.sop.docIsvInfo;

type ContextRef = {
  examineRef: Ref<Undefinedable<ExtendedModalApi>>;
  settingGroupRef: Ref<Undefinedable<ExtendedModalApi>>;
  settingKeysRef: Ref<Undefinedable<ExtendedModalApi>>;
};

export function createCrudOptions(
  props: CreateCrudOptionsProps<SopIsvInfoModel.SopIsvInfoResultVO, ContextRef>,
): CreateCrudOptionsRet<SopIsvInfoModel.SopIsvInfoResultVO> {
  const selectedRowKeys = ref<string[]>([]);
  function handleViewKeys(isvId?: string) {
    props.context?.settingKeysRef.value?.setData({
      type: ActionEnum.VIEW,
      isvId,
    });
    props.context?.settingKeysRef.value?.open();
  }
  return {
    crudOptions: {
      request: {
        pageRequest: SopIsvInfoApi.pageRequest,
        addRequest: SopIsvInfoApi.addRequest,
        editRequest: SopIsvInfoApi.editRequest,
        delRequest: SopIsvInfoApi.delRequest,
        infoRequest: SopIsvInfoApi.infoRequest,
      },
      actionbar: {
        buttons: {
          add: {
            show: hasPermission(permCode.add),
          },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            removeFn: SopIsvInfoApi.remove,
            role: permCode.delete,
          }),
        },
      },
      search: {
        col: { span: 6 },
        // container: { layout: 'multi-line' },
      },
      form: {
        wrapper: {
          is: 'a-modal',
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: '220px',
        buttons: {
          settingKeys: {
            text: '设置秘钥',
            size: 'small',
            type: 'link',
            show: compute((context: ComputeContext) => {
              const row = context.row;
              return (
                (row.creationMethod === CreationMethodEnum.CREATE ||
                  (row.creationMethod === CreationMethodEnum.APPLY_FOR &&
                    [AuditStatusEmum.PASS].includes(row.auditStatus))) &&
                hasPermission(permCode.settingKeys)
              );
            }),
            click: (context) => {
              props.context?.settingKeysRef.value?.setData({
                type: ActionEnum.ADD,
                isvId: context.row.id,
              });
              props.context?.settingKeysRef.value?.open();
            },
          },
          settingGroup: {
            text: '设置分组',
            size: 'small',
            type: 'link',
            show: hasPermission(permCode.settingGroup),
            click: (context) => {
              props.context?.settingGroupRef.value?.setData({
                isvId: context.row.id,
              });
              props.context?.settingGroupRef.value?.open();
            },
          },
          examine: {
            dropdown: true,
            text: '审核',
            size: 'small',
            type: 'link',
            show: compute((context: ComputeContext) => {
              const row = context.row;
              return (
                row.creationMethod === CreationMethodEnum.APPLY_FOR &&
                [AuditStatusEmum.APPLYING].includes(row.auditStatus) &&
                hasPermission(permCode.examine)
              );
            }),
            click: (context) => {
              props.context?.examineRef.value?.setData({
                isvId: context.row.id,
              });
              props.context?.examineRef.value?.open();
            },
          },
          edit: { dropdown: true, show: hasPermission(permCode.edit) },
          view: { dropdown: true, show: true },
          remove: { dropdown: true, show: hasPermission(permCode.delete) },
          copy: { show: false },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        tenantId: {
          title: $t('devOperation.sop.sopIsvInfo.tenantId'),
          type: 'dict-select',
          dict: dict({
            value: 'id',
            label: 'name',
            async getData() {
              return await DefTenantApi.query({});
            },
          }),
          column: {
            component: {
              type: 'text',
            },
          },
          search: { show: true },
        },
        appId: {
          title: $t('devOperation.sop.sopIsvInfo.appId'),
          type: 'text',
          search: { show: true },
          addForm: {
            show: true,
            component: {
              disabled: true,
              placeholder: '系统自动生成',
            },
          },
          editForm: {
            show: true,
            component: {
              disabled: true,
              placeholder: '系统自动生成',
            },
          },
          column: { show: false },
        },
        keys: {
          title: $t('devOperation.sop.sopIsvInfo.keys'),
          type: 'text',
          column: {
            width: 80,
            cellRender({ row }) {
              return (
                <Button
                  block
                  onClick={() => handleViewKeys(row.id)}
                  type="link"
                >
                  查看
                </Button>
              );
            },
          },
          form: {
            show: false,
            submit: false,
          },
        },
        name: {
          title: $t('devOperation.sop.sopIsvInfo.name'),
          type: 'text',
          search: { show: true },
        },
        status: {
          title: $t('devOperation.sop.sopIsvInfo.status'),
          type: 'dict-radio',
          dict: STATE_NUMBER_CONSTANT_DICT,
          search: { show: true },
          addForm: { value: 1 },
          column: { width: 70 },
        },
        remark: {
          title: $t('devOperation.sop.sopIsvInfo.remark'),
          type: 'textarea',
          search: { show: false },
          column: { ellipsis: true, showTitle: true },
        },
        expirationTime: {
          title: '有效期',
          type: 'datetimerange',
          addForm: { show: true },
          editForm: { show: true },
          form: {
            component: {
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
            },
          },
          // 表单回显时，处理数据格式
          valueBuilder({ value, row, key }) {
            if (value !== null && row) {
              row[key] = [row.startExpirationTime, row.endExpirationTime];
            }
          },
          // 表单提交前，处理数据格式
          valueResolve({ form, key }) {
            if (form && form[key]) {
              form.startExpirationTime = form[key]?.[0];
              form.endExpirationTime = form[key]?.[1];
            }
          },
          column: {
            customRender: ({
              record,
            }: {
              record: SopIsvInfoModel.SopIsvInfoResultVO;
            }) => {
              const row = record;
              if (
                row.startExpirationTime !== null &&
                row.endExpirationTime !== null
              ) {
                return `${row.startExpirationTime}至${row.endExpirationTime}`;
              } else if (
                row.startExpirationTime === null &&
                row.endExpirationTime !== null
              ) {
                return `截止至${row.endExpirationTime}`;
              } else if (
                row.startExpirationTime !== null &&
                row.endExpirationTime === null
              ) {
                return `${row.startExpirationTime}至永久`;
              } else {
                return '永久有效';
              }
            },
            show: true,
          },
        },
        creationMethod: {
          title: $t('devOperation.sop.sopIsvInfo.creationMethod'),
          type: 'dict-radio',
          dict: backendDict(DictEnum.SOP_ISV_CREATION_METHOD),
          search: { show: true },
          addForm: { show: false },
          editForm: { show: false },
          column: { show: true, width: 80 },
        },
        auditStatus: {
          title: $t('devOperation.sop.sopIsvInfo.auditStatus'),
          type: 'dict-radio',
          dict: backendDict(
            { type: 'AuditStatusEnum', isEnum: true },
            DictValueType.number,
          ),
          addForm: { show: false },
          editForm: { show: false },
          column: {
            show: true,
          },
        },
        auditTime: {
          title: $t('devOperation.sop.sopIsvInfo.auditTime'),
          type: 'datetime',
          addForm: { show: false },
          editForm: { show: false },
          column: {
            show: true,
            formatter({ row, value }) {
              return row.creationMethod === 0 ? '-' : value;
            },
          },
        },
        submissionTime: {
          title: $t('devOperation.sop.sopIsvInfo.submissionTime'),
          type: 'datetime',
          addForm: { show: false },
          editForm: { show: false },
          column: {
            show: true,
            formatter({ row, value }) {
              return row.creationMethod === 0 ? '-' : value;
            },
          },
        },
        reviewComments: {
          title: $t('devOperation.sop.sopIsvInfo.reviewComments'),
          type: 'text',
          search: { show: false },
          addForm: { show: false },
          editForm: { show: false },
          column: {
            show: false,
            formatter({ row, value }) {
              return row.creationMethod === 0 ? '-' : value;
            },
          },
        },

        ...createdTimeColumn({}),
      },
    },
  };
}

export const frontRules = (
  _crudExpose: CrudExpose,
  _mode: ActionEnum,
): FormRulesExt => {
  return {};
};
